use std::rc::Rc;
use std::cell::RefCell;

#[derive(Debug, PartialEq, Eq)]
pub struct TreeNode {
    pub val: i32,
    pub left: Option<Rc<RefCell<TreeNode>>>,
    pub right: Option<Rc<RefCell<TreeNode>>>,
}

struct Solution;

impl Solution {

    // 自己解法
//    pub fn remove_leaf_nodes(root: Option<Rc<RefCell<TreeNode>>>, target: i32) -> Option<Rc<RefCell<TreeNode>>> {
//        if let Some(root_rc) = root.clone() {
//            let left = root_rc.borrow().left.clone();
//            let right = root_rc.borrow().right.clone();
//            Solution::traverse(left, target, root_rc.clone(), 0);
//            Solution::traverse(right, target, root_rc.clone(), 1);
//            let root_borrow = root_rc.borrow();
//            if root_borrow.left.is_none() && root_borrow.right.is_none() && root_borrow.val == target {
//                return None;
//            }
//            return root;
//        }
//        None
//    }
//    // 0 代表左 1代表右
//    fn traverse(root: Option<Rc<RefCell<TreeNode>>>, target: i32, parent: Rc<RefCell<TreeNode>>, sign: usize) {
//        if let Some(root_rc) = root {
//            let left = root_rc.borrow().left.clone();
//            let right = root_rc.borrow().right.clone();
//            Solution::traverse(left, target, root_rc.clone(), 0);
//            Solution::traverse(right, target, root_rc.clone(), 1);
//            let left = root_rc.borrow().left.clone();
//            let right = root_rc.borrow().right.clone();
//            let val = root_rc.borrow().val;
//            if left.is_none() && right.is_none() && val == target {
//                if sign == 0 {
//                    parent.borrow_mut().left = None;
//                } else {
//                    parent.borrow_mut().right = None;
//                }
//            }
//        }
//    }


    pub fn remove_leaf_nodes(root: Option<Rc<RefCell<TreeNode>>>, target: i32) -> Option<Rc<RefCell<TreeNode>>> {
        if let Some(root_rc) = root.clone() {
            let left = root_rc.borrow().left.clone();
            let right = root_rc.borrow().right.clone();
            if left.is_some() {
                root_rc.borrow_mut().left = Solution::remove_leaf_nodes(left, target);
            }
            if right.is_some() {
                root_rc.borrow_mut().right = Solution::remove_leaf_nodes(right, target);
            }
            let root_borrow = root_rc.borrow();
            return if root_borrow.left.is_none() && root_borrow.right.is_none() && root_borrow.val == target {
                None
            } else {
                root
            };
        }
        None
    }
}

fn main() {
    Solution::remove_leaf_nodes(None, 0);
}
